package com.yangjun.utils;

import java.io.Serializable;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisClientLocalUtils implements Serializable {
	private static final long serialVersionUID = 5946615349370117706L;
	private JedisPool jedisPool;// 非切片连接池
	
	
	public RedisClientLocalUtils()
    {
        initialPool();
    }
	 /**
     * 初始化非切片池
     */
    private void initialPool()
    {
        // 池基本配置
		JedisPoolConfig config = new JedisPoolConfig();
		// 如果赋值为-1，则表示不限制
		config.setMaxTotal(10);
		config.setMaxIdle(10);
		// 最大的等待时间
		config.setMaxWaitMillis(10000);
		config.setTestOnBorrow(true);
		config.setTestOnReturn(false);
        jedisPool = new JedisPool(config, "10.0.22.100", 6379, 30000);// 30000 timeout
    }

    /**
     * 还回到连接池
     */
	public void returnResource(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}


	/**
	 * 设置juid的失效时长
	 * @param juid
	 * @param jedis
	 */
	public void setTimeSecond(String juid,Jedis jedis){
		jedis.expire(juid, 86400);//1天  60s*60m*24h
//		jedis.expire(juid, 3600);//1个小时  60s*60m

	}
	public boolean setKeyValue(String key,String value){
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.set(key, value);
			setTimeSecond(key, jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}

		return true;
	}
	
	
	public String getValue(String key){
		String value="";
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			if(jedis.exists(key)){
				value = jedis.get(key);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return value;
	}

	
	/**
	 * 清除redis缓存
	 * @return
	 */
	public boolean clearRedis(){
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.flushDB();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return true;
	}


//	public static void main(String[] args) {
//		RedisClientLocalUtils rc = new RedisClientLocalUtils();
//		Jedis jedis = rc.jedisPool.getResource();
//		System.out.println("jedis--" + jedis);
//		String waregeneralname = rc.getValue("waregeneralname");
//		System.out.println("waregeneralname===="+waregeneralname);
//		String brandname = rc.getValue("brandname");
//		System.out.println("brandname===="+brandname);
//		String manufacturername = rc.getValue("manufacturername");
//		System.out.println("manufacturername===="+manufacturername);
//		String warename = rc.getValue("warename");
//		System.out.println("warename===="+warename);
//	}

}
